﻿using System;
using System.Collections;
using System.Threading;
using Microsoft.SPOT;

namespace Flight.Controller.Managers
{
    /// <summary>
    /// Utility manager thread to execute action each 2 seconds.
    /// </summary>
    public class UtilityManager
    {
        private static UtilityManager _Instance;
        private static bool _Stop = false;

        private ArrayList _utilities = new ArrayList();

        /// <summary>
        /// Initializes a new instance of th <see cref="UtilityManager"/> class.
        /// </summary>
        private UtilityManager()
        {
            new Thread(new ThreadStart(Run)) { Priority = ThreadPriority.BelowNormal }.Start();
        }

        /// <summary>
        /// Thread execution.
        /// </summary>
        private void Run()
        {
            while (!_Stop)
            {
                Thread.Sleep(2000);

                lock (_utilities)
                {
                    foreach (object o in _utilities)
                        ((IUtilityHandler)o).Execute();
                }
            }
        }

        /// <summary>
        /// Gets current instance.
        /// </summary>
        public static UtilityManager Instance
        {
            get
            {
                return _Instance ?? (_Instance = new UtilityManager());
            }
        }

        /// <summary>
        /// Stops manager execution.
        /// </summary>
        public static void StopManager()
        {
            _Stop = true;
        }

        /// <summary>
        /// Register utility to be executed.
        /// </summary>
        /// <param name="handler">Handler to register.</param>
        public void RegisterUtility(IUtilityHandler handler)
        {
            if (handler != null)
            {
                lock (_utilities)
                    _utilities.Add(handler);
            }
        }
    }
}
